package handler

import (
	"chat_user/api/request"
	"chat_user/inter/dao"
	"chat_user/inter/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func CreateCommon(c *gin.Context) {
	var req request.CreateCommon
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var com model.Commons
	dao.GetOneByFields(&model.Commons{}, &com)
	if com.Text == req.Text {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "此条数据以已重复",
			"data": nil,
		})
		return
	}
	com = model.Commons{
		Text:  req.Text,
		Image: req.Image,
		Video: req.Video,
		Like:  req.Like,
	}
	if !dao.Create(&com) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "发布动态失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": com,
	})
}

func FindCommon(c *gin.Context) {
	var com []model.Commons
	dao.GetListByFields(&model.Commons{}, &com)
	var coms []*model.Commons
	for _, v := range com {
		dao.GetOneByField(&model.Commons{Like: v.Like}, &v)
	}
	for _, v := range com {
		coms = append(coms, &v)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": coms,
	})
}
